import 'package:flutter_chubao/config/app_config.dart';
import 'package:flutter_chubao/models/model_home_user.dart';
import 'package:flutter_chubao/models/model_product.dart';
import 'package:flutter_chubao/route/app_route_name.dart';
import 'package:flutter_chubao/tools/app_log.dart';
import 'package:flutter_chubao/tools/app_tool_toast.dart';
import 'package:flutter_chubao/tools/tool_app/app_dio_client.dart';
import 'package:flutter_chubao/tools/tool_app/app_dio_response.dart';
import 'package:flutter_chubao/widgets/app_alert_dialog.dart';
import 'package:flutter_gromore/callback/gromore_reward_callback.dart';
import 'package:flutter_gromore/config/gromore_reward_config.dart';
import 'package:flutter_gromore/flutter_gromore.dart';
import 'package:get/get.dart';

import 'app_home_state.dart';

typedef EnumConvertFunction<T> = T Function(String value);

/// @description:
/// @author
/// @date: 2023-12-13 10:17:16
class AppHomeLogic extends GetxController {
  final state = AppHomeState();
  getHomeData() async {
    // AppDioResponse response =
    //     await AppDioClient.get('/mini/chubao/article/list', queryParameters: {

    AppDioResponse response = await AppDioClient.post(
      '/mini/chubao/ad/query',
    );
    if (response.ok) {
      state.homeUserEntity = HomeUserEntity.fromJson(response.data);
      // final arr0 = <ModelProduct>[];
      // response.data['data'].forEach((v) {
      //   arr0.add(ModelProduct.fromJson(v));
      // });
      // state.productList = arr0;
      update();
    }
  }

  getHomeRemmendData() async {
    AppDioResponse response = await AppDioClient.post(
        '/mini/chubao/article/list',
        data: {'type': state.type, 'page': state.currentPage});

    if (state.currentPage > 1) {
      state.refreshController.loadComplete();
    } else {
      state.refreshController.refreshCompleted();
    }
    if (response.ok) {
      List<ModelProduct> list = (response.data['list'] as List).map((v) {
        ModelProduct model = ModelProduct.fromJson(v);
        if (state.type == 2) {
          model.isLock = true;
        }

        return model;
      }).toList();
      if (state.currentPage == 1) {
        state.productList = list;
      } else {
        state.productList.addAll(list);
      }
      update();
    } else {
      if (state.currentPage > 1) {
        state.refreshController.loadFailed();
      } else {
        state.refreshController.refreshFailed();
      }
      // state.refreshController.refreshFailed();
    }
  }

  lockArticle(ModelProduct product) async {
    if (product.isLock == true) {
      Get.toNamed(AppRouteName.appWebPage,
          arguments: {'title': product.title ?? '', 'url': product.content});
    } else {
      Get.dialog(APPAlertDialog(
          infoStr: '确定要花费600积分解锁该文章?',
          contentStr: '解锁时长：3小时',
          actionBtns: (index) async {
            // DLog(index);
            if (index == 1) {
              AppDioResponse response =
                  await AppDioClient.post('/mini/chubao/article/unlock', data: {
                'articleId': product.id,
              });
              if (response.ok) {
                product.isLock = true;
                AppToolToast.showToast('解锁成功');
                // state.productList = (response.data['list'] as List)
                //     .map((v) => ModelProduct.fromJson(v))
                //     .toList();
                getHomeData();
                update();
              }
              // AppManagerUser.userLoginOut();
            }
          }));
    }
  }

  // clickVideoGG(ModelProduct product) async {
  //   // /mini/chubao/reward
  //    AppDioResponse response =
  //       await AppDioClient.post('/mini/chubao/article/unlock', data: {
  //     'articleId': product.id,
  //   });
  //   if (response.ok) {
  //     product.isLock = true;
  //     // state.productList = (response.data['list'] as List)
  //     //     .map((v) => ModelProduct.fromJson(v))
  //     //     .toList();
  //     update();
  //   }
  // }

  getVideoJl() async {
    AppDioResponse response = await AppDioClient.post(
      '/mini/chubao/reward',
    );
    if (response.ok) {
      getHomeData();
    }
  }

  Future<void> loadRewardAd() async {
    String rewardAdId = await FlutterGromore.loadRewardAd(GromoreRewardConfig(
        adUnitId:
            (AppConfig.configEntity?.rewardVideoList ?? []).first?.adCodeId ??
                ''));
    DLog((AppConfig.configEntity?.rewardVideoList ?? []).first?.adCodeId ?? '');
    if (rewardAdId.isNotEmpty) {
      showRewardAd(rewardAdId);
    }
  }

  /// 激励视频广告
  Future<void> showRewardAd(String rewardId) async {
    await FlutterGromore.showRewardAd(
        rewardId: rewardId,
        callback: GromoreRewardCallback(onRewardVerify: (bool verify) {
          DLog("恭喜你，获得奖励,,,,$verify");
          getVideoJl();
          if (verify) {
            // 如果需要在关闭广告后再判断，可以先把这个值用变量存储一下，在onAdClose回调中根据变量的值进行判断
            print("恭喜你，获得奖励");
          }
        }));
  }

  @override
  void onInit() {
    super.onInit();
    getHomeData();
    getHomeRemmendData();
  }
}
